/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kizitonwose.calendarview.ui;

import com.kizitonwose.calendarview.model.CalendarDay;

import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;

import java.util.List;

/**
 * WeekHolder
 *
 * @since 2021-02-26
 */
public class WeekHolder {
    private List<DayHolder> dayHolders;
    private DirectionalLayout container;

    /**
     * WeekHolder
     *
     * @param dayHolders List
     */
    public WeekHolder(List<DayHolder> dayHolders) {
        this.dayHolders = dayHolders;
    }

    Component inflateWeekView(DirectionalLayout parent) {
        container = new DirectionalLayout(parent.getContext());
        DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig();
        layoutConfig.width = DirectionalLayout.LayoutConfig.MATCH_CONTENT;
        layoutConfig.height = DirectionalLayout.LayoutConfig.MATCH_CONTENT;
        container.setLayoutConfig(layoutConfig);
        container.setOrientation(DirectionalLayout.HORIZONTAL);

        for (DayHolder dayHolder : dayHolders) {
            container.addComponent(dayHolder.inflateDayView(container));
        }
        return container;
    }

    /**
     * bindWeekView
     *
     * @param daysOfWeek List
     */
    public void bindWeekView(List<CalendarDay> daysOfWeek) {
        if (daysOfWeek == null || daysOfWeek.isEmpty()) {
            // 隐藏
            container.setVisibility(Component.HIDE);
        } else {
            // 否则显示，必须设置否则导致某行数据缺失
            container.setVisibility(Component.VISIBLE);
        }

        // 布局变化了需进行刷新重绘（否则每个月的星期行数不同时，高度无法恢复，会使用上一个component的缓存高度）
        container.invalidate();

        int size = dayHolders.size();
        for (int index = 0; index < size; index++) {
            DayHolder dayHolder = dayHolders.get(index);
            if (daysOfWeek != null && index < daysOfWeek.size()) {
                dayHolder.bindDayView(daysOfWeek.get(index));
            } else {
                dayHolder.bindDayView(null);
            }
        }
    }

    /**
     * reloadDay
     *
     * @param day CalendarDay
     * @return reloadViewIsNecessary
     */
    public boolean reloadDay(CalendarDay day) {
        for (DayHolder dayHolder : dayHolders) {
            if (dayHolder.reloadViewIfNecessary(day)) {
                return true;
            }
        }
        return false;
    }
}
